package com.cskaoyan.service;

import com.cskaoyan.bean.po.CommonData;
import com.cskaoyan.bean.po.MarketGoods;
import com.cskaoyan.bean.po.MarketTopic;
import com.cskaoyan.bean.po.MarketTopicExample;
import com.cskaoyan.bean.vo.front.topic.FrontTopicVo;
import com.cskaoyan.mapper.MarketGoodsMapper;
import com.cskaoyan.mapper.MarketTopicMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName:FrontTopicServiceImpl
 * @Auther: HeXianZu
 * @Description:
 * @Date: 2022/10/15 11:28
 */
@Service
public class FrontTopicServiceImpl implements FrontTopicService {

    @Autowired
    MarketTopicMapper marketTopicMapper;

    @Override
    public CommonData list(Integer page, Integer limit) {
        // 查询前使用PageHelper进行分页预处理
        PageHelper.startPage(page,limit);

        // 调用mapper层进行SQL查询
        // 使用Example作为参数进行查询
        MarketTopicExample example = new MarketTopicExample();
        List<MarketTopic> marketTopics = marketTopicMapper.selectByExample(example);

        // 将查询的数据进行分页
        PageInfo<MarketTopic> pageInfo = new PageInfo<>(marketTopics);

        // 创建返回对象并将分页数据进行处理然后返回
        return CommonData.data(pageInfo);
    }

    @Autowired
    MarketGoodsMapper marketGoodsMapper;

    @Override
    public FrontTopicVo detail(Integer id) {
        // 调用mapper层进行SQL查询
        // 通过主键id作为参数进行查询
        MarketTopic marketTopic = marketTopicMapper.selectByPrimaryKey(id);

        // 取出查询出的主题中的goods，进行goods的查询
        String[] goods = marketTopic.getGoods();
        // 遍历goods获取goodsId,将其作为参数查询对应goods信息
        // 将查询出的Goods信息添加进对应的List
        List<MarketGoods> goodsList = new ArrayList<>();
        for (String good : goods) {
            Integer goodsId = Integer.parseInt(good);
            MarketGoods marketGoods = marketGoodsMapper.selectByPrimaryKey(goodsId);
            goodsList.add(marketGoods);
        }
        // 将查询到的数据进行封装并返回
        FrontTopicVo frontTopicVo = new FrontTopicVo();
        frontTopicVo.setTopic(marketTopic);
        frontTopicVo.setGoods(goodsList);
        return frontTopicVo;
    }
}
